class CourseOperations:
    def __init__(self, courses,students_data):
        self.courses = courses['courses']
        self.students = students_data['students']

    def get_all_courses(self):
        courses = [
            {
                'id': course['courseId'],
                'name': course.get('title', 'Untitled course'),
            }
        for course in self.courses]
    
        id_width = max(len(course['id']) for course in courses) + 2
        name_width = max(len(course['name']) for course in courses) + 2

    
        header = (f"{'ID':<{id_width}}{'Course name':<{name_width}}")
        separator = "=" * (id_width + name_width)
    
        rows = []
        for course in courses:
            row = (f"{course['id']:<{id_width}}"
                f"{course['name']:<{name_width}}")
            rows.append(row)
    
        return "\n".join([header, separator] + rows)
        
    def get_course_information(self, course_id):
        course = next((c for c in self.courses if c['courseId'] == course_id), None)
        if not course:
            return None
        
        info_lines = [
            "═" * 40,
            f"Course information - {course['courseId']}",
            "═" * 40
        ]
        
        info_lines.extend([
            f"Course name: {course.get('title', 'N/A')}",
            f"Affiliation: {course.get('department', 'N/A')}",
            f"Credits: {course.get('credits', 'N/A')}",
            f"Professor: {course.get('professor', 'N/A')}"
        ])
        
        if 'schedule' in course:
            schedule = course['schedule']
            info_lines.extend([
                "\n🕒 Course time:",
                f" week: {', '.join(schedule.get('days', []))}",
                f" time: {schedule.get('time', 'N/A')}",
                f" classroom: {schedule.get('room', 'N/A')}"
            ])
        
        if 'prerequisites' in course and course['prerequisites']:
            info_lines.append(f"\n📚 Prerequisites: {', '.join(course['prerequisites'])}")
        
        if 'description' in course:
            info_lines.append(f"\n📝 Course description:\n  {course['description']}")
        
        info_lines.append("═" * 40)
        return "\n".join(info_lines)
        
    def get_course_students(self,course_id):
        course_id = course_id.upper()
        course_exists = any(c['courseId'].upper() == course_id for c in self.courses)
        if not course_exists:
            return None
    
        enrolled = [s['username'] for s in self.students if course_id in [c.upper() for c in s.get('followed_courses', [])]]

        return enrolled if enrolled else []

    
    def get_course_schedule(self, course_id):
        course = self.get_course_information(course_id)
        return course['schedule'] if course else None
    
    def validate_prerequisites(self, student_username, course_id):
        course = next((c for c in self.courses if c['courseId'] == course_id), None)
        if not course:
            raise ValueError(f"Course {course_id} does not exist")

        prerequisites = course.get('prerequisites', [])
        if not prerequisites:
            return True, []  

        student = next((s for s in self.students if s['username'] == student_username), None)
        if not student:
            raise ValueError("Student not found")

        missing_prereqs = [
            prereq for prereq in prerequisites 
            if prereq not in student['followed_courses']
        ]

        return (not missing_prereqs, missing_prereqs)